package cn.jsp.dao;

import cn.jsp.domain.Stu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class StuDao {
    @Autowired DataSource dataSource;//自动绑定

    public List<Stu> query(){
        List<Stu> stus=new ArrayList<>();
        try (
            Connection connection =dataSource.getConnection();
            PreparedStatement preparedStatement=connection.prepareStatement("select *from stu");
            ResultSet resultSet=preparedStatement.executeQuery())
        {
            while(resultSet.next()){
                Stu stu=new Stu(resultSet.getString("name"),resultSet.getInt("age"));
                stus.add(stu);
                System.out.println(resultSet.getString("name"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return stus;
    }
}

